<?php
require('./Wechat.php');

function is_json($string) {
  json_decode($string);
  return (json_last_error() == JSON_ERROR_NONE);
}

class MyWechat extends Wechat {

  protected function onText() {
    if (file_exists("pm25.json")){
      $history = filemtime("pm25.json");
    }else{
      $history = false;
    }
    if($history && time() - $history < 1 * 60 * 60){
      $pm25 = file_get_contents("pm25.json");
    }else{
      $pm25 = file_get_contents("http://www.pm25.in/api/querys/only_aqi.json?city=wuhan&token=ykvs4yfeuRqvPHnxDfQc");
      $f = fopen("pm25.json", "w");
      fwrite($f, $pm25);
    }
    $data = json_decode($pm25);
    if(json_last_error() == JSON_ERROR_NONE){
      $aqi = $data[count($data)-1];
      $content = "区域：武汉\n";
      $content .= "空气指数：" . $aqi->aqi . "\n";
      $content .= "空气质量：" . $aqi->quality . "\n";
      $content .= "主要污染：" . $aqi->primary_pollutant . "\n";
      $content .= str_replace(array("T","Z"), array(" ",""), $aqi->time_point);
    }else{
      $content = "暂无数据。。。";
    }
    $this->responseText("$content");
  }

}

$wechat = new MyWechat('itjesse', TRUE);
$wechat->run();
